package com.suanfa.node;

/**
 * 反转单向链表 时间复杂度O(n) 空间复杂度O(1)
 */
public class NodeReverse {

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        ListNode listNode6 = new ListNode(6);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;
        listNode5.next = listNode6;

        ListNode single = reverse(listNode1);

        while(single != null){
            System.out.println(single.value);
            single = single.next;
        }

    }


    public static ListNode reverse(ListNode head){
        if(head == null ){//当前是最后一个节点
            return null;
        }

        ListNode pre = null;
        ListNode current = head;
        ListNode next = null;

        while(current != null){
            next = current.next;
            current.next = pre;
            pre = current;
            current = next;
        }
        return pre;

    }


}



